#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import datetime
import collections
from django.http import JsonResponse
from django.db.models import Count
from django.shortcuts import HttpResponse,render,redirect
from web import models
# ''' 项目概览-项目问题新增图表 '''
def mychart01(request,project_id):
    """ 在概览页面生成highcharts所需的数据 """
    # ''' 处理x轴的时间数据 '''
    today = datetime.datetime.now().date()
    date_dict = collections.OrderedDict()
    for i in range(0, 30):
        # 取30天内的数据情况
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]
    # date_dict {'2023-03-16':[1678896000000,0],'2023-03-15':[1678896000000,0]}
    # select xxxx,1 as ctime from xxxx
    # select id,name,email from table;
    # select id,name, strftime("%Y-%m-%d",create_datetime) as ctime from table; #extra相当于 as
    # "DATE_FORMAT(web_transaction.create_datetime,'%%Y-%%m-%%d')"
    # result = models.Issues.objects.filter(project_id=project_id,
    #                                       create_datetime__gte=today - datetime.timedelta(days=30)).extra(
    #     select={'ctime': "strftime('%%Y-%%m-%%d',web_issues.create_datetime)"}).values('ctime').annotate(ct=Count('id'))
    result = models.Issues.objects.filter(project_id=project_id,
                                          create_datetime__gte=today - datetime.timedelta(days=30)).extra(
        select={'ctime': "DATE_FORMAT(web_issues.create_datetime,'%%Y-%%m-%%d')"}).values('ctime').annotate(ct=Count('id'))
    # gt 大于__gte 大于等于 lt小于 lte小于等于，values('ctime').annotate(ct=Count('id'))根据ctime分组
    for item in result:
        # 2023-03-16时间作为key,修改值（列表）中的第二项目也就是 合计数的位置
        date_dict[item['ctime']][1] = item['ct']
    print(date_dict.values())
    return JsonResponse({'status': True, 'data': list(date_dict.values())})